package com.parknfly.mycalendar.calendar.adapter;


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.parknfly.mycalendar.R;
import com.parknfly.mycalendar.calendar.model.MonthData;
import com.parknfly.mycalendar.calendar.model.SelectedRange;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


public class MyDateAdapter extends RecyclerView.Adapter<MyDateAdapter.ViewHolder> {

    private final List<MonthData> months = new ArrayList<>();
    /* 1. 全局唯一区间 */
    private final SelectedRange global = new SelectedRange(); // 统一区间

    public MyDateAdapter() {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_MONTH, 1); // 从本月1号开始

        for (int i = 0; i < 3; i++) { // 本月 + 未来2个月 = 3个月
            months.add(new MonthData(c.get(Calendar.YEAR),
                    c.get(Calendar.MONTH)));
            c.add(Calendar.MONTH, 1);
        }
    }

    /* 2. 当任意月重新选择后，清掉旧区间并全局刷新 */
    private void updateRange(Calendar s, Calendar e) {
        global.startCal = s;
        global.endCal = e;
        notifyItemRangeChanged(0, months.size());

        if (dateHandler != null) {
            if (s != null && e != null) {
                dateHandler.getDate(s, e);
            }
        }
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_date_adapter, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder h, int position) {
        MonthData data = months.get(position);
        h.tvDate.setText(data.getMonthTitle());
        // 3. 把全局区间交给 SubDateAdapter
        SubDateAdapter sub = new SubDateAdapter(data.year, data.month,
                global,
                (s, e) -> updateRange(s, e));
        h.recyclerView2.setLayoutManager(new GridLayoutManager(h.itemView.getContext(), 7));
        h.recyclerView2.setAdapter(sub);

    }


    @Override
    public int getItemCount() {
        return months.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvDate;

        RecyclerView recyclerView2;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvDate = itemView.findViewById(R.id.tvDate);
            recyclerView2 = itemView.findViewById(R.id.recyclerView2);
        }
    }

    DateHandler dateHandler;

    public void setDateHandler(DateHandler dateHandler) {
        this.dateHandler = dateHandler;
    }

    public interface DateHandler {
        void getDate(Calendar b, Calendar e);
    }
}
